package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author itheima
 * @Date 2022/5/6 9:32
 */
@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //获取请求URI
        String requestURI = req.getRequestURI();


        //定义要放行的请求URI数组
        String[] URIS = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //URI匹配工具：将统配符字符和具体字符串进行比对
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String uri : URIS) {
            // "/backend/**" ?  "/backend/js/request.js"
            if (pathMatcher.match(uri, requestURI)) {
                chain.doFilter(request, response);
                return;
            }
        }


        //2.未登录：从token中取值没有取到，直接返回一个R数据，前端会自动跳转到login.html

        //2.1获取请求头：token的值
        String token = req.getHeader("Authorization");
        System.out.println("token值为{}" + token);
        //判断token是否存在
        if (StringUtils.isBlank(token)) {
            resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }

        //2.2判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        try {
            //是否是过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
        }

        //3.已登录：claimsBody中取值能够取到，直接放行
        Integer empId = (Integer) claimsBody.get("id");
        if (empId != null) {
            BaseContext.setThreadLocalId(empId.longValue());
            chain.doFilter(request, response);
        }
    }
}
